#!/usr/bin/env python
# -*- coding:utf-8 -*-

import ConfigParser
import urllib
import urllib2
import base64
from xml.dom.minidom import parseString
import xml.dom.minidom

try:
    import json
except ImportError:
	import simplejson as json

def ini_getBingKey():
	"""
	get the ini api key from ini configure file
	"""
	cf = ConfigParser.ConfigParser()
	cf.read('bing_api_key.ini')
	iniKey = cf.get('bing_api', 'key')
	return iniKey

def data_bingSearch(temp_ip):
	"""
	get bing result of this ip
	"""
	query = "ip:"+temp_ip
	payload = {}
	payload['Query'] = "'"+query+"'"
	url = 'https://api.datamarket.azure.com/Bing/Search/v1/Web?' + urllib.urlencode(payload)

	sAuth = 'Basic ' + base64.b64encode(':i'+ini_getBingKey())

	headers = {}
	headers['Authorization'] = sAuth
	try:
		request = urllib2.Request(url, headers=headers)
		response = urllib2.urlopen(request)
		file_data = response.read()

		return file_data
	except Exception as e:
		print e
	return -1

def trXmlToList(xmlData):
	"""
	translate xml to list
	"""
	xmlList = []
	DOMTree = xml.dom.minidom.parseString(xmlData)
	root = DOMTree.documentElement
	properties = root.getElementsByTagName("m:properties")
	for properti in properties:
		titles = properti.getElementsByTagName("d:Title")
		resultTitle = titles[0].firstChild.data
		urls = properti.getElementsByTagName("d:Url")
		resultUrl = urls[0].firstChild.data
		xmlList.append([resultUrl, resultTitle])
	if (len(xmlList)<1):
		return -1
	else:
		return xmlList
